package com.spdg.ring.offline;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
import cn.wolf.tools.CommonUtils;
import cn.wolf.tools.Frequency;
import cn.wolf.tools.Log;
import cn.wolf.tools.MD5;
import cn.wolf.tools.MathUtil;
import cn.wolf.tools.SdCardTool;

import com.spdg.ring.R;
import com.spdg.ring.ZipDownloadActivity;
import com.spdg.ring.common.Config;
import com.spdg.ring.datamgr.ArticleDataMgr;
import com.spdg.ring.datamgr.MenuDataMgr;
import com.spdg.ring.sqlite.model.Menu;

/**
 * <p>Title:  离线包下载管理</p>
 * <p>Description:  </p>
 * <p>@author: caijj                </p>
 * <p>Copyright: Copyright (c) 2012    </p>
 * <p>Company: HX Co., Ltd.          </p>
 * <p>Create Time: 2012-11-22             </p>
 * <p>Update Time:                     </p>
 * <p>Updater:                         </p>
 * <p>Update Comments:                 </p>
 */
public class OfflineDownloadManager {

	private static OfflineDownloadManager mInstance = new OfflineDownloadManager();

	private OfflineDownloadManager() {
		listeners = new ArrayList<DownloadListener>();
	}

	public static OfflineDownloadManager getInstance() {
		if (mInstance == null)
			mInstance = new OfflineDownloadManager();
		return mInstance;
	}

	private Activity mContext;

	private boolean loading;
	private boolean loadingSuccess;

	private List<Progress> ps;
	private ZipDownload zipDownload;

	private Frequency fre = new Frequency(500);

	private NotificationManager notificationManager;
	private Notification mNotification;
	private static final int NOTIFY_ID = 1001;

	public String getKey(String url) {
		return MD5.getMD5Str(url);
	}

	public void start(Activity context) {
		this.mContext = context;

		if (loading) {
			Toast.makeText(context, context.getString(R.string.offline_loading), Toast.LENGTH_SHORT)
					.show();
			return;
		}

		// 网络异常，网络异常，请检查网络
		if (!CommonUtils.isNetConnectionAvailable(context)) {
			Toast.makeText(context, context.getString(R.string.network_error), Toast.LENGTH_SHORT)
					.show();
			return;
		}

		if (!SdCardTool.isMounted()) { // sd卡未挂载
			Toast.makeText(context, context.getString(R.string.sdcard_unmounted),
					Toast.LENGTH_SHORT).show();
			return;
		}

		final int length = 4;
		ps = new ArrayList<Progress>(length);

		for (int i = 0; i < length; i++) {
			Menu menu = MenuDataMgr.getInstance().getMenu(context, i);
			if(menu != null){
				String name = menu.getName();
				String url = menu.getSrc() + "&file=" + menu.getFile();
				String key = getKey(url);
				Progress p = new Progress();
				p.url = url;
				p.name = name;
				p.key = key;
				p.fileName = key;
				p.filePath = Config.SDCARD_OFFLINE_PACKAGE;
				ps.add(p);
			}
		}

		zipDownload = new ZipDownload(ps);
		zipDownload.setDownloadListener(new DownloadListenerMgr());
		zipDownload.execute();

		loading = true;

		notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);

		createNotification(R.drawable.ic_launcher);

		sendNofify(ps.get(0)); // 发送广播

		Toast.makeText(mContext, mContext.getString(R.string.offline_title), Toast.LENGTH_SHORT)
				.show();
	}

	public void cancel() {
		if (loading) {
			loading = false;
			zipDownload.cancel();
			zipDownload = null;
		}

		clearNotify();
	}

	public boolean loadSuccess() {
		return loadingSuccess;
	}

	class DownloadListenerMgr implements DownloadListener {
		@Override
		public void onProgress(Progress progress) {
			sendNofify(progress);

			if (listeners == null || listeners.isEmpty())
				return;

			for (DownloadListener l : listeners) {
				l.onProgress(progress);
			}
		}

		@Override
		public void onError(DownloadException e) {
			Log.e("download error. message:" + e.getMessage());
			cancel();

			if (listeners == null || listeners.isEmpty())
				return;

			for (DownloadListener l : listeners) {
				l.onError(e);
			}
		}

		@Override
		public void onPostExecute(final List<Progress> list) {
			Toast.makeText(mContext, "下载完成", Toast.LENGTH_SHORT).show();
			loadingSuccess = true; // 下载完成
			loading = false;
			clearNotify();
			if (listeners != null && !listeners.isEmpty()) {
				for (DownloadListener l : listeners) {
					l.onPostExecute(list);
				}
			}
		}

		@Override
		public void onPostProgress(final int index, final Progress progress) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					if (progress != null) {
						OfflineZipUitl.parseZip(progress.filePath, progress.fileName);
						Menu menu = MenuDataMgr.getInstance().getMenu(mContext, index);
						OfflineZipUitl.save2sqlite(mContext, menu);

						if (index == 3) { // 刷新数据
							ArticleDataMgr.getInstance().loadDataSqlite(mContext);
						}
					}
				}
			}).start();
		}
	}

	private List<DownloadListener> listeners;

	public void addDownloadListener(DownloadListener l) {

		if (listeners == null) {
			listeners = new ArrayList<DownloadListener>();
		}

		if (l != null) {
			listeners.add(l);
			if (zipDownload != null)
				zipDownload.onManualProgress();
		}
	}

	public void removeDownloadListener(DownloadListener l) {
		if (listeners != null && !listeners.isEmpty()) {
			listeners.remove(l);
		}
	}

	public void clearTemp() {
		SdCardTool.deleteAll(Config.SDCARD_OFFLINE_PACKAGE);
	}

	// =======================================================
	// 通知栏
	// =======================================================

	public void sendNofify(final Progress p) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				if (mContext != null && fre.toRun()) {

					String title = mContext.getString(R.string.offline_title);
					String content = "";
					if (p.total == p.complete) {
						content = mContext.getString(R.string.offline_progress_success);
					} else {
						content = mContext.getString(R.string.offline_progress_desc);
						content = String.format(content, p.name,
								MathUtil.percent(p.total, p.complete));
					}

					Notification notification = mNotification;

					notification.setLatestEventInfo(mContext, title, content,
							notification.contentIntent);
					notificationManager.notify(NOTIFY_ID, notification);
				}
			}
		}).start();
	}

	private void createNotification(int icon) {
		Notification notification = new Notification();
		notification.defaults = Notification.DEFAULT_LIGHTS;
		notification.flags |= Notification.FLAG_NO_CLEAR;
		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		notification.icon = R.drawable.ic_launcher;

		RemoteViews contentView = new RemoteViews(mContext.getPackageName(),
				R.layout.status_bar_latest_event_content);
		if (icon != 0) {
			contentView.setImageViewResource(R.id.icon, icon);
		}

		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.setClass(mContext, ZipDownloadActivity.class);

		PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		notification.contentIntent = contentIntent;
		// notification.contentView = contentView;

		mNotification = notification;
	}

	public void clearNotify() {
		loading = false;
		notificationManager.cancel(NOTIFY_ID);
	}

}
